//
//  UserLevel.swift
//  LeGou
//
//  Created by lxm on 2022/8/5.
//

import UIKit

class UserLevel: ZMViewController, UIScrollViewDelegate {
    //MARK: --------------------属性--------------------
    // 滚动处理者
    let scrllHandler = ScrollFloatHandler()
    
    var info = ZMUtil.fastNilBehavior(type: MineModels.ServiceProviderInfo.self)
    //MARK: --------------------UI控件--------------------
    let nav = NavigationBarView()
    
    let scrolleView = ScrollBgView()
    // 黑色背景
    let blackBgView = UIView().then({$0.backgroundColor = "#191B20".zm.hex()})
    
    let header = UserLevelHeaderView()
    
    let listGoods = VIPMallGoodsList().then { vc in
        vc.isGussLike = true
    }
    
    let loading = XMLoadingView()
    // 猜你喜欢头部
    let guessHeader = UIView().then { v in
        let stack = ZMUtil.stackView(axis: .horizontal, spacing: 8)
        let leftIcon = ZMUtil.imageView(imageName: "detail_zuo")
        let rightIcon = ZMUtil.imageView(imageName: "detail_zuo")
        let label = ZMUtil.label(title: "猜你喜欢", color: UIColor.zm.color333333(), font: UIFont.systemFont(ofSize: 14))
        
        stack.addArrangedSubview(leftIcon)
        stack.addArrangedSubview(label)
        stack.addArrangedSubview(rightIcon)

        v.addSubview(stack)
        stack.snp.makeConstraints { make in
            make.center.equalToSuperview()
        }
    }
    
    let contentStack = ZMUtil.stackView(axis: .vertical)
    //MARK: --------------------生命周期--------------------
    override func viewDidLoad() {
        super.viewDidLoad()
        setUI()
        addConstraints()
        bindAction()
        getInfo()
    }
    
    //MARK: --------------------UI--------------------
    func setUI() {
        //view
        view.backgroundColor = "#F5F5F5".zm.hex()
        
        //nav
        hbd_barHidden = true
        hbd_barStyle = .black
        view.addSubview(nav)
        nav.titleLabel.text = "服务商等级"
        nav.titleLabel.textColor = .white
        nav.autoBack = true
        nav.backgroundColor = "#191B20".zm.hex()
        nav.setRightButton { btn in
            btn.setTitle("规则详情", for: .normal)
            btn.setTitleColor(.white, for: .normal)
            btn.titleLabel?.font = UIFont.systemFont(ofSize: 14)
        } _: {
            CommonService.shared.goWeb(type: .serviceLevelRules)
        }
        
        // scrolleView
        view.addSubview(scrolleView)
        scrolleView.addSubview(blackBgView)
        contentStack.addArrangedSubview(header)
        contentStack.addArrangedSubview(guessHeader)
        scrolleView.addSubview(contentStack)
        scrolleView.gestureDelegate = scrllHandler
        scrolleView.delegate = self
        scrolleView.showsHorizontalScrollIndicator = false
        scrllHandler.bgScollView = scrolleView
        scrllHandler.floatView = guessHeader
        scrllHandler.subScollObjc = listGoods
        
        // listGoods
        addChild(listGoods)
        contentStack.addArrangedSubview(listGoods.view)
    }
    
    
    func addConstraints() {
        nav.snp.makeConstraints { make in
            make.top.left.right.equalToSuperview()
        }
        
        scrolleView.snp.makeConstraints { make in
            make.top.equalTo(nav.snp.bottom)
            make.right.bottom.left.equalToSuperview()
        }
        
        blackBgView.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            make.top.equalToSuperview().offset(-200)
            make.height.equalTo(255 + 200)
        }
        
        contentStack.snp.makeConstraints { make in
            make.edges.equalToSuperview()
            make.centerX.equalToSuperview()
        }
        
        guessHeader.snp.makeConstraints { make in
            make.height.equalTo(48)
        }
        
        listGoods.view.snp.makeConstraints { make in
            make.height.equalTo(scrolleView.snp.height)
        }
    }
    
    
    //MARK: --------------------methods--------------------
    
    
    func bindAction() {
        info.subscribe(onNext:{ [unowned self] resp in
            guard let resp = resp else {return}
            
            self.header.levelBtn.setTitle(MineService.shared.LevelStr(level: resp.serviceProviderLevel), for: .normal)
            self.header.currentActivityNum.text = "\(resp.totalActivity.zm.toString(keep: 4))"
            self.header.nowLevel.text = MineService.shared.LevelStr(level: resp.serviceProviderLevel)
            self.header.toLevel.text = MineService.shared.LevelStr(level: resp.nextServiceProviderLevel)
            self.header.progress.progress = Float(resp.speed / 100)
            if resp.serviceProviderLevel == resp.nextServiceProviderLevel {
                self.header.tips.text = "您已达到最高等级"
            } else {
                var condition = [String]()
                if resp.differenceActivity > 0 {
                    condition.append("\(resp.differenceActivity.zm.toString(keep: 4)) 活跃度")
                }
                if resp.differenceTeamNum > 0 {
                    condition.append("\(resp.differenceTeamNum) 邀请人数")
                }
                
                var des = "还差 "
                for i in 0 ..< condition.count {
                    if i == 0 {
                        des.append(condition[i])
                    } else {
                        des.append("和 ")
                        des.append(condition[i])
                    }
                }
                des.append("升级至 \(MineService.shared.LevelStr(level: resp.nextServiceProviderLevel))")

                self.header.tips.text = des
            }
        }).disposed(by: disposeBag)
        
        header.onRightNow.rx.tap.subscribe(onNext:{ [unowned self] resp in
            CATransaction.setCompletionBlock {
                guard let tab = UIApplication.shared.keyWindow?.rootViewController as? UITabBarController else {return}
                tab.selectedIndex = 1
            }
            CATransaction.begin()
            self.navigationController?.popViewController(animated: true)
            CATransaction.commit()
        }).disposed(by: disposeBag)
    }
    
    func getInfo() {
        loading.showInView(fatherView: view)
        MineAPI.serviceProviderInfo.rxRequest(type: MineModels.ServiceProviderInfo.self).subscribe(onNext:{ [unowned self] resp in
            self.info.accept(resp)
            self.loading.hideView(anmation: true)
        }, onError: { e in
            self.loading.showError(e.localizedDescription)
        }).disposed(by: disposeBag)
    }
    //MARK: --------------------delegate--------------------
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        scrllHandler.scrollViewDidScroll(scrollView)
    }
}
